#include <fstream>
#include <iostream>
#include <sstream>
#include <TFile.h>
#include <TH1F.h>
#include <TKey.h>
#include <TMath.h>

void ge_calib_pos_hist_precond(std::string const &);
double search_peak(TH1F const *);

void ge_calib_pos_hist_precond(std::string const &filename)
{
  TFile file(filename.c_str());
  std::ofstream ofile("hist_precond.txt");
  for (int clu = 0; 8 > clu; ++clu)
    for (int cry = 0; 3 > cry; ++cry)
      for (int seg = 0; 6 > seg; ++seg) {
        std::ostringstream oss;
        oss << "EGamCl" << clu << "Cr" << cry << "Se" << seg;
        ofile << search_peak(dynamic_cast<TH1F *>(
            file.GetKey(oss.str().c_str())->ReadObj())) << '\n';
      }
}

double search_peak(TH1F const *hist)
{
  int max = 0;
  int max_i = 0;
  int value;
  for (int i = 0; 120 > i; ++i) {
    value = hist->GetBinContent(1 + i);
    if (value > max) {
      max = value;
      max_i = i;
    }
  }
  double sum_fx = 0.;
  double sum_f = 0.;
  for (int i = max_i - 10; i <= max_i + 10; ++i) {
    value = hist->GetBinContent(1 + i);
    sum_fx += (i + 950) * value;
    sum_f += value;
  }
  double x = sum_fx / sum_f;
  return TMath::IsNaN(x) ? 0. : x;
}
